package com.example.fw;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;

public class ContactHelper extends HelperBase{

	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}

	public void initContactCreation() {
		click(By.linkText("add new"));
	}

	public void fillContactForm(ContactData contact, boolean hasGroupSelector) {
	  type(By.name("firstname"), contact.firstName);
	  type(By.name("lastname"), contact.lastName);
	  type(By.name("address"), contact.addressFirst);
	  type(By.name("home"), contact.homeTel);
	  type(By.name("mobile"), contact.mobileTel);
	  type(By.name("work"), contact.workTel);
	  type(By.name("email"), contact.emailFirst);
	  type(By.name("email2"), contact.emailSecond);
	  selectByText(By.name("bday"), contact.birthDay);
	  selectByNumber(By.name("bmonth"), contact.birthMonth);
	  type(By.name("byear"), contact.birthYear);
	  type(By.name("address2"), contact.addressSecond);
	  type(By.name("phone2"), contact.homeSecond);
	  if (hasGroupSelector) {
	   selectByText(By.name("new_group"), contact.userGroup = SelectRandomGroup());
	  }
	}
	
	private String SelectRandomGroup() {
        List<WebElement> options = driver.findElements(By.xpath("//form/select[3]/option"));
        Random rnd = new Random();
        return options.get(rnd.nextInt(options.size())).getText();
}

	public void returnToContactPage() {
		click(By.linkText("home page"));
	}


	public void submitContactCreation() {
	click(By.name("submit"));
	}

	public void deleteContact() {
	click(By.xpath("//input[@value='Delete']"));
	  
	}

	public void initContactModification(int index) {
	click(By.xpath("//tr[@name='entry'][" + (index+1) + "]/td[7]/a/img"));
		
	}

	public void submitContactModification() {
	click(By.xpath("//input[@value='Update']"));
	  		
	}

	public List<ContactData> getContacts() {
	       List<ContactData> contacts = new ArrayList<ContactData>();
		   List<WebElement> rows = getContactRows();
		   for (WebElement row : rows) {
			   ContactData contact = new ContactData();
               contact.lastName = getLastNameInRow(row);
               contacts.add(contact);		
		}
		     return contacts;
	}

	private String getLastNameInRow(WebElement row) {
		    return row.findElement(By.xpath("./td[2]")).getText();
	}

	private List<WebElement> getContactRows() {
			return driver.findElements(By.xpath("//tr[@name='entry']"));
	}
}

	
